package com.ruike.alisurface.ui.mainPage;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.GoodsBean;
import com.ruike.alisurface.bean.rkAdBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.mqtt.ServiceUtils;
import com.ruike.alisurface.services.MyImageService;
import com.ruike.alisurface.ui.adapter.GoodsCarListAdapter;
import com.ruike.alisurface.ui.adapter.GoodsListAdapter;
import com.ruike.alisurface.ui.dialog.GoodsInfoDialog;
import com.ruike.alisurface.ui.payPage.PayForWeChatFaceActivity;
import com.ruike.alisurface.ui.payPage.SelectPayTypeActivity;
import com.ruike.alisurface.utils.DensityUtil;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;
import com.voodoo.lib_utils.imageLoader.GlideCacheUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 程序入口主界面
 */
public class MainActivity extends BaseAty implements GoodsCarListAdapter.OnItemDeleteClickListener, GoodsListAdapter.OnGoodsItemClickListener {

    @BindView(R.id.main_goodsList_recv)
    RecyclerView mainGoodsListRecv;
    @BindView(R.id.main_toPay_btn)
    Button mainToPayBtn;
    @BindView(R.id.main_nullNetwork_llayout)
    LinearLayout nullNetworkLlayout;
    @BindView(R.id.main_refresh_btn)
    Button refreshBtn;
    @BindView(R.id.main_showCarList_rlayout)
    RelativeLayout showCarListRlayout;
    @BindView(R.id.main_carNumber_tv)
    TextView carNumberTv;
    @BindView(R.id.main_popBack_view)
    View popupWindowBgView;
    @BindView(R.id.main_currentMoney_tv)
    TextView currentMoneyTv;

    List<GoodsBean> goodsBeans; // 商品列表
    List<GoodsBean> goodsCarBeans; // 购物车的商品列表
    GoodsListAdapter goodsListAdapter; // 商品列表适配器

    double currentMoney; // 当前选中商品的总价格
    boolean isOpenAdv;//是否开启广告
    LinearLayout root_view;//父布局
    List<String> mImgs = new ArrayList<>();
    PopupWindow popupWindow;
    boolean canAddCar = false; // 是否可以添加购物车
    private boolean isItemCanClick = false; // 商品数据是否可点击

    @Override
    protected void onStart() {
        super.onStart();
        // 启动界面倒计时
        startCountdownTimer(60, null, null);
    }

    @Override
    protected void onPause() {
        super.onPause();
        CountdownTimercancal();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void initViews() {
        isOpenAdv = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) != Constant.ADV_TYPE_NONE;
        L.i("sp 广告类型：", ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE));
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        root_view = findViewById(R.id.main_productContent_llayout);
        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                L.i("手动开始请求商品数据");
                if (!isNetConnect()) {
                    showErrorTip("无网络连接，无法更新数据");
                }
                requestSlotDataList();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!ServiceUtils.isServiceRunning(this, MQTTService.class.getName())) {
            L.e(" 检测到MQTTService  未启动   开始启动");
            ServiceUtils.startService(this, MQTTService.class);
        }
        canAddCar = false; // 刚加载界面的时候不点击商品列表中的item
        mainToPayBtn.setEnabled(true);// 结算按钮可点击
        GlideCacheUtil.getInstance().clearImageMemoryCache(this);
        // 如果有广告，那么开启界面倒计时
        if (isOpenAdv) {
            startCountdownTimer(120, null, VideoAdvActivity.class);
        }
        L.i("商品主页==" + this.getClass().getName());

        L.i("onResume==删除购物车数据并清空展示布局");
        MyApplication.finalDbUtils.deleteAll(CarGoodsBeans.class);
        isItemCanClick = false;
        // 清购物车
        if (goodsCarBeans == null) {
            goodsCarBeans = new ArrayList<>();
        }
        deleteCar(goodsCarBeans);
        goodsCarBeans.clear();
        // 清商品列表
        if (goodsBeans == null) {
            goodsBeans = new ArrayList<>();
        }
        goodsBeans.clear();
        // 清商品列表
        if (goodsListAdapter == null) {
            goodsListAdapter = new GoodsListAdapter(this, goodsBeans);
        } else {
            goodsListAdapter.notifyDataSetChanged();
        }
        goodsListAdapter.setData(goodsBeans);
        L.i("重新加载界面清空购物车之后，购物车中的数据：" + MyApplication.finalDbUtils.findAll(CarGoodsBeans.class));

        setCurrentMoney();
        try {
            MchApiHttp.getrk_ad(this);
        } catch (Exception e) {
            L.e("获取广告异常：" + e.getMessage());
        } finally {
            requestSlotDataList();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        canAddCar = hasFocus;
    }

    @OnClick({R.id.main_showCarList_rlayout, R.id.main_toPay_btn})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.main_showCarList_rlayout: // 展示购物车
                if (goodsCarBeans.size() <= 0) {
                    showErrorTip("暂无商品");
                    return;
                }
                showShopCarPopupWindow(showCarListRlayout);
                break;
            case R.id.main_toPay_btn: // 去付款
                L.i("  去付款次数  ");
                if (goodsCarBeans.size() > 0) {
                    canAddCar = false;
                    mainToPayBtn.setEnabled(false);
                    List<CarGoodsBeans> goodsCarBeanss = new ArrayList<>();
                    for (GoodsBean goodsBean : goodsCarBeans) {
                        CarGoodsBeans goodsBeans = new CarGoodsBeans();
                        goodsBeans.setCount(goodsBean.getCount());
                        goodsBeans.setPrice(goodsBean.getPrice());
                        goodsBeans.setProductid(goodsBean.getProductid());
                        goodsBeans.setProductimg(goodsBean.getProductimg());
                        goodsBeans.setProductname(goodsBean.getProductname());
                        List<Integer> slotIndexs = new ArrayList<>();
                        slotIndexs.add(goodsBean.getSlotIndex());
                        goodsBeans.setSlotIndexs(String.valueOf(slotIndexs));
                        goodsCarBeanss.add(goodsBeans);
                    }
                    MyApplication.finalDbUtils.saveList(goodsCarBeanss);
                    startActivity(SelectPayTypeActivity.class, null);
//                    startActivity(PayForWeChatFaceActivity.class, null);
                } else {
                    showErrorTip(getResources().getString(R.string.pleaseChooseToBuyGoodsStr));
                }
                break;
        }
    }

    /**
     * 展示购物车弹窗
     *
     * @param showCarListRlayout 对应的锚点位置
     */
    private void showShopCarPopupWindow(RelativeLayout showCarListRlayout) {

        // 如果正在显示弹窗直接将弹窗关闭
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            return;
        }

        // 设置展示的View
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_shop_car_layout, null, false);
        RecyclerView recyclerView = contentView.findViewById(R.id.dialogShopCarLayout_carList_recv);

        GoodsCarListAdapter goodsCarListAdapter = new GoodsCarListAdapter(this, goodsCarBeans);
        goodsCarListAdapter.setOnItemDeleteClickListener(this);
        recyclerView.setAdapter(goodsCarListAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        contentView.findViewById(R.id.dialogShopCarLayout_clearCar_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                deleteCar(goodsBeans);
                deleteCar(goodsCarBeans);
                goodsCarBeans.clear();
            }
        });

        // 构造 PopupWindow
        popupWindow = new PopupWindow(this);
        popupWindow.setContentView(contentView);
        popupWindow.setWidth(DensityUtil.dp2px(this, 786));
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置pop透明效果
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xFF0000));
        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
        popupWindow.setFocusable(true);
        // 设置pop可点击，为false点击事件无效，默认为true
        popupWindow.setTouchable(true);
        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
        popupWindow.setOutsideTouchable(true);
        // 相对于锚点View号正下面，同时可以设置偏移量
        popupWindow.showAtLocation(showCarListRlayout, Gravity.BOTTOM, 0, 95);
        popupWindowBgView.setVisibility(View.VISIBLE);
        // 设置pop关闭监听，用于改变背景透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindowBgView.setVisibility(View.GONE);
            }
        });
    }

    rkAdBean rkAdBean;
    ArrayList<String> advList;

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("get_rk_ad")) {
            rkAdBean = GsonUtils.json2Model(requestJsonStr, rkAdBean.class);
            mImgs.clear();
            mImgs.add(rkAdBean.getData().getAlert_page());
            advList = new ArrayList<>();
            advList.add(rkAdBean.getData().getSale_banner());
            advList.add(rkAdBean.getData().getOutgoods_banner());
            advList.add(rkAdBean.getData().getAlert_page());
            startTopAdvFileService(Constant.topAdvpath, advList);
        }
    }

    @Override
    public void onFailure(String requestUrl, String requestMsg) {
        super.onFailure(requestUrl, requestMsg);
        L.i("Error====" + requestUrl + "====" + requestMsg);
        if (requestUrl.endsWith("Get_Productinfo")) {
            showErrorTip("信息获取失败，请检查网络...");
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("get_rk_ad")) {
            ShareUtils.getInstance().putBoolean(ShareKey.GET_RK_AD, false);
            titleBar_root_rlayout.setBackgroundResource(R.color.colorTitleBar);
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals("adv_activity") && event.getMessage().equals("跳转广告页")) {
            Intent intent = new Intent(this, VideoAdvActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        if (event.getType().equals("adv_type") && event.getMessage().equals("无广告")) { //判断无广告
            isOpenAdv = ShareUtils.getInstance().getInt(ShareKey.ADV_TYPE, Constant.ADV_TYPE_NONE) == Constant.ADV_TYPE_NONE;
            initTitleBar(isOpenAdv);
            CountdownTimercancal();
            return;
        }
        if (event.getType().equals("货道更新")) {
            L.i("更新货道", "货道更新中");
            requestSlotDataList();
            return;
        }
        if (event.getType().equals("商品数据")) {
            L.i("商品数据", "商品数据返回成功");
            L.i("返回数据：" + event.getMessage());
            nullNetworkLlayout.setVisibility(View.GONE);
            mHandler.removeCallbacksAndMessages(null);
            removeProgressDialog();
            if (goodsBeans != null) {
                goodsBeans.clear();
                if (goodsCarBeans != null && goodsCarBeans.size() > 0) {
                    goodsCarBeans.clear();
                }
            }
            goodsBeans = GsonUtils.jsonArray2ModelList(event.getMessage(), GoodsBean.class);
            L.i("返回数据：" + goodsBeans);
            if (goodsBeans.size() <= 0) {
                showErrorTip("当前无可购买的商品");
                startCountdownTimer(3, null, null);
                return;
            }
            goodsListAdapter.setData(goodsBeans);
            isItemCanClick = true;
            return;
        }
        if (event.getType().equals("商品数据异常")) {
            L.i("商品数据异常", event.getMessage());
            mHandler.removeCallbacksAndMessages(null);
            removeProgressDialog();
            showLongTip(event.getMessage(), 5000);
            nullNetworkLlayout.setVisibility(View.VISIBLE);
            if (goodsBeans != null) {
                goodsBeans.clear();
                goodsListAdapter.setData(goodsBeans);
            }
            startCountdownTimer(5, null, null);
        }
        // 只是更新商品列表图片
        if (event.getType().equals("商品图片")) {
            if (goodsListAdapter != null) {
                L.i("商品图片更新", event.getMessage());
                goodsListAdapter.notifyDataSetChanged();
            }
        }
    }

    Handler mHandler = new Handler();

    /**
     * 请求货道数据列表
     */
    public void requestSlotDataList() {
        L.i("开始请求商品数据");
        showProgressDialog("加载数据中，请等待。。。");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.i("主动取消请求弹框");
                removeProgressDialog();
                EventBus.getDefault().post(new MsgEventBus("商品数据异常", "请求超时"));
            }
        }, 32 * 1000);
        setGoodsListView();
        startService(new Intent(this, MyImageService.class));
    }

    /**
     * 设置商品列表
     */
    public void setGoodsListView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3); // 布局管理器所需参数，上下文
        mainGoodsListRecv.setLayoutManager(gridLayoutManager); // 设置布局管理器，参数 linearLayout
        mainGoodsListRecv.setHasFixedSize(true);
        goodsListAdapter = null;
        goodsListAdapter = new GoodsListAdapter(this, goodsBeans);
        goodsListAdapter.setHasStableIds(true);
        goodsListAdapter.setOnGoodsItemClickListener(this);
        mainGoodsListRecv.setAdapter(goodsListAdapter);
    }

    /**
     * 商品列表点击商品
     *
     * @param imageView 点击商品的图片
     * @param index     点击商品的下标
     * @param clickBean 点击商品对象
     */
    @Override
    public void onGoodsClick(ImageView imageView, int index, GoodsBean clickBean) {
        L.i("添加商品到购物车 == " + clickBean);
        if (isItemCanClick) {
            addCar(index, clickBean);
        }
    }

    /**
     * 删除购物车中的数据
     *
     * @param index     删除的下标
     * @param goodsBean 删除的对象
     */
    @Override
    public void onGoodsDeleteClick(int index, GoodsBean goodsBean) {
        // 删除是单个删除，但是删除方法需要传入一个列表对象
        List<GoodsBean> deleteGoods = new ArrayList<>();
        deleteGoods.add(goodsBean);
        deleteCar(deleteGoods);
    }

    /**
     * 添加购物车
     *
     * @param index     商品列表的索引
     * @param clickBean 点击的商品
     */
    @SuppressLint("StringFormatInvalid")
    private void addCar(int index, GoodsBean clickBean) {
        if (canAddCar) {
            if (goodsCarBeans == null) {
                goodsCarBeans = new ArrayList<>();
            }
            if (goodsCarBeans.size() < ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)) {
                if (clickBean != null && clickBean.getCount() > 0) {
                    L.i("添加商品");

                    // 设置商品列表中的数据，库存减1，并更新商品列表
                    clickBean.setCount(clickBean.getCount() - 1);
                    if (goodsBeans == null || goodsBeans.size() < index) {
                        L.i("goodsBeans == null = " + (goodsBeans == null) + "     goodsBeans.size() = " + (goodsBeans == null ? 0 : goodsBeans.size()) + "     index = " + index);
                    } else {
                        goodsBeans.set(index, clickBean);
                    }
                    goodsListAdapter.setData(goodsBeans);

                    // 数据表修改好之后添加到购物车数据表
                    goodsCarBeans.add(clickBean);
                    setCurrentMoney();

                } else {
                    if (clickBean == null) {
                        L.e("点击的商品数据为空");
                    }
                    // 选的这个商品没库存了
                    showErrorTip(getResources().getString(R.string.goodsSoldOutStr));
                    L.i("选中的商品没库存了：" + clickBean.toString());
                }
            } else {
                // 最多购买 X 个商品 的提示
                showErrorTip(String.format(Locale.ENGLISH, getResources().getString(R.string.maxPurchaseQuantityStr), ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT)));
                L.i("购物车满了，最多购买件数设置的是：" + ShareUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT));
            }
        }
    }

    /**
     * 删除购物车数据
     *
     * @param deleteGoodsBeans 点击删除的目标对象列表
     */
    private void deleteCar(List<GoodsBean> deleteGoodsBeans) {
        if (deleteGoodsBeans == null || deleteGoodsBeans.size() == 0) {
            return;
        }

        List<GoodsBean> waitDeleteList = new ArrayList<>();

        // 遍历传入的数组
        for (GoodsBean deleteGoodsBean : deleteGoodsBeans) {
            int deleteProductIndex = deleteGoodsBean.getSlotIndex();
            for (int i = 0; i < goodsBeans.size(); i++) {
                GoodsBean goodsBean = goodsBeans.get(i);
                if (goodsBean.getSlotIndex() == deleteProductIndex) {
                    goodsBean.setCount(goodsBean.getCount() + 1);
                    waitDeleteList.add(deleteGoodsBean);
                    break;
                }
            }
        }

        for (GoodsBean deleteGoodsBean : waitDeleteList) {
            goodsCarBeans.remove(deleteGoodsBean);
        }

        setCurrentMoney();

        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }

    }

    /**
     * 设置价格以及展示的View
     */
    private void setCurrentMoney() {

        L.i("currentMoney:" + currentMoney);

        currentMoney = 0;
        // 遍历添加金额
        for (GoodsBean goodsBean : goodsCarBeans) {
            currentMoney += goodsBean.getPrice();
        }

        // 展示购物车数组中元素个数
        carNumberTv.setText(String.valueOf(goodsCarBeans.size()));

        // 设置价格展示
        currentMoneyTv.setText(String.format(Locale.ENGLISH, "%.2f", currentMoney));
        // 设置购物车数量展示
        if (goodsCarBeans == null || goodsCarBeans.size() <= 0) {
            carNumberTv.setText(String.valueOf(0));
            carNumberTv.setVisibility(View.GONE);
        } else {
            carNumberTv.setText(String.valueOf(goodsCarBeans.size()));
            carNumberTv.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

}
